package com.redhipps.hips.client.command;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.redhipps.hips.client.HipsApp;
import com.redhipps.hips.client.io.IOService;
import com.redhipps.hips.client.io.ReaderCallback;
import com.redhipps.hips.client.model.Context;
import com.redhipps.hips.client.model.Institution;
import com.redhipps.hips.client.widget.InstitutionList;
import com.redhipps.hips.client.widget.SelectionListener;

public class ListInstitutionsCommand extends HipsCommand<List<Institution>> {

  @Override
  public void execute(final AsyncCallback<List<Institution>> callback) {
    IOService ioService = ioService();
    ioService.list(context(), Institution.class, new ReaderCallback<Institution>() {
      public void onFailure(Throwable caught) {
        GWT.log("Institution listing failed.", caught);
        callback.onFailure(caught);
      }
      public void onSuccess(List<Institution> result) {
        final Context context = context();
        String login = context.loginKey().toString();
        Label label = new Label("Institutions for " + login);
        InstitutionList list = new InstitutionList(context, result);
        list.setItemSelectionListener(new SelectionListener<Institution>() {
          public void itemSelected(Institution model, Widget widget) {
            context.pushInstitution(model);
            new InstitutionDetailsCommand().execute();
          }
        });
        VerticalPanel vp = new VerticalPanel();
        vp.add(label);
        vp.add(list);
        HipsApp.setContents(vp);
        callback.onSuccess(result);
      }
    });
  }

}
